package cn.shengchao.wecom.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.shengchao.wecom.configure.WxCpConfiguration;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.RandomUtils;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpAgentJsapiSignature;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="https://github.com/0katekate0">Wang_Wong</a>
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/wx/cp/js/{corpId}")
@SaIgnore
public class WxJsController {
    @PostMapping("/{agentId}/getConfigSignature")
    public Map getConfigSignature(
            @PathVariable String corpId,
            @PathVariable Integer agentId,
            String uri) throws WxErrorException {
        System.out.println("uri2=" + uri);
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置，请核实！", agentId));
        }
       // WxJsapiSignature wxJsapiSignature = wxCpService.createJsapiSignature(uri);
        WxJsapiSignature wxJsapiSignature = createJsapiSignature(uri,  agentId);
        String signature = wxJsapiSignature.getSignature();
        String nonceStr = wxJsapiSignature.getNonceStr();
        long timestamp = wxJsapiSignature.getTimestamp();

        Map res = new HashMap<String, String>();
        res.put("appId", corpId); // 必填，企业微信的corpID
        res.put("timestamp", timestamp); // 必填，生成签名的时间戳
        res.put("nonceStr", nonceStr); // 必填，生成签名的随机串
        res.put("signature", signature); // 必填，签名，见 附录-JS-SDK使用权限签名算法
        return res;
    }
    @PostMapping("/{agentId}/getJsConf")
    public Map getJsConf(
            @PathVariable String corpId,
            @PathVariable Integer agentId,
            String uri) throws WxErrorException {
        System.out.println("uri1=" + uri);
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置，请核实！", agentId));
        }
      //  WxCpAgentJsapiSignature wxJsapiSignature = wxCpService.createAgentJsapiSignature(uri);
        WxCpAgentJsapiSignature wxJsapiSignature = createAgentJsapiSignature(uri,  agentId);
        String signature = wxJsapiSignature.getSignature();
        String nonceStr = wxJsapiSignature.getNonceStr();
        long timestamp = wxJsapiSignature.getTimestamp();

        Map res = new HashMap<String, String>();
        res.put("appId", corpId); // 必填，企业微信的corpID
        res.put("timestamp", timestamp); // 必填，生成签名的时间戳
        res.put("nonceStr", nonceStr); // 必填，生成签名的随机串
        res.put("signature", signature); // 必填，签名，见 附录-JS-SDK使用权限签名算法
        return res;
    }
    public WxJsapiSignature createJsapiSignature(String url, Integer agentId) throws WxErrorException {
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        long timestamp = System.currentTimeMillis() / 1000L;
        String noncestr = RandomUtils.getRandomStr();
        String jsapiTicket = wxCpService.getJsapiTicket(false);
        System.out.println("jsapiTicket=" + jsapiTicket);
        String signature = SHA1.genWithAmple(new String[]{"jsapi_ticket=" + jsapiTicket, "noncestr=" + noncestr, "timestamp=" + timestamp, "url=" + url});
        WxJsapiSignature jsapiSignature = new WxJsapiSignature();
        jsapiSignature.setTimestamp(timestamp);
        jsapiSignature.setNonceStr(noncestr);
        jsapiSignature.setUrl(url);
        jsapiSignature.setSignature(signature);
        jsapiSignature.setAppId(wxCpService.getWxCpConfigStorage().getCorpId());
        return jsapiSignature;
    }

    public WxCpAgentJsapiSignature createAgentJsapiSignature(String url, Integer agentId) throws WxErrorException {
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        long timestamp = System.currentTimeMillis() / 1000L;
        String noncestr = RandomUtils.getRandomStr();
        String jsapiTicket = wxCpService.getAgentJsapiTicket(false);
        System.out.println("jsapiAgentTicket=" + jsapiTicket);
        String signature = SHA1.genWithAmple(new String[]{"jsapi_ticket=" + jsapiTicket, "noncestr=" + noncestr, "timestamp=" + timestamp, "url=" + url});
        WxCpAgentJsapiSignature jsapiSignature = new WxCpAgentJsapiSignature();
        jsapiSignature.setTimestamp(timestamp);
        jsapiSignature.setNonceStr(noncestr);
        jsapiSignature.setUrl(url);
        jsapiSignature.setSignature(signature);
        jsapiSignature.setCorpid(wxCpService.getWxCpConfigStorage().getCorpId());
        jsapiSignature.setAgentid(wxCpService.getWxCpConfigStorage().getAgentId());
        return jsapiSignature;
    }
    public static String genNonce() {
        return bytesToHex(Long.toString(System.nanoTime()).getBytes(StandardCharsets.UTF_8));
    }

    public static String bytesToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

}
